import {ComputedRef} from "vue";
import {IHub} from "@/store/modules/crossPage/crossPage";

export interface IActions {
  method: string; // 方法名
  params: any; // 方法参数
}

/**
 * 解决KeepAlive缓存页面，导致的跨页面交互的问题
 * e.g.
 * 页面A 跳转到 页面B， 页面B提交表单后需要页面A刷新
 */
export function useCrossPage(moduleName: string, context: any) {
  const store = useStore();
  // const _moduleName = ref(moduleName);

  const currentModuleHub:ComputedRef<IHub[]> = computed(() => {
    return store.state.crossPage.hubs[moduleName]
  })

  const registerEvents = (moduleName: string) => {
    store.dispatch("crossPage/registerEvents", moduleName)
  }

  const checkSavedEvents = async () => {
    for (let i=0; i<currentModuleHub.value.length; i++) {
      const storedMethod = currentModuleHub.value[i];
      // @ts-ignore
      await context[storedMethod.method](storedMethod.params);
    }

    store.commit("crossPage/clearModule", moduleName);
  }

  const storeEvent = (method: string, params?: any) => {
    store.commit("crossPage/storeEvent", {
      moduleName,
      method: method,
      params
    })
  }

  onActivated(async () => {
    registerEvents(moduleName);
    await checkSavedEvents()
  })

  return {
    storeEvent
  }
}
